package tq.com.tqstudent.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.google.gson.Gson;
import com.lib.common.utils.Tips;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.net.URLEncoder;

import tq.com.tqstudent.Constants;
import tq.com.tqstudent.bean.ThirdPartyLoginBean;
import tq.com.tqstudent.net.ok.StringCallback;

/**
 * @Author rames
 * @date 2019/3/12 17:23
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
    private IWXAPI api;
    private BaseResp resp = null;
    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        String result = "";
        if (resp != null) {
            resp = resp;
        }

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()){
                    // 授权登录
                    case 1:
                        login(((SendAuth.Resp) resp).code);
                        break;

                        // 分享
                    case 2:
//                        Tips.showLongTips(this, "分享成功");
                        this.finish();
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "操作取消";
                Tips.showLongTips(this, result);
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "操作被拒绝";
                Tips.showLongTips(this, result);
                finish();
                break;
            default:
                result = "返回";
                Tips.showLongTips(this, result);
                finish();
                break;
        }
    }

    private void login(String code){
        /*
         * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
         */
        String get_access_token = getCodeRequest(code);
        OkGo.<String>get(get_access_token).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response1) {
                try {
                    if (!response1.equals("")) {
                        JSONObject response = new JSONObject(response1.body());
                        String access_token = response.getString("access_token");
                        String openid = response.getString("openid");
                        String get_user_info_url = getUserInfo(access_token, openid);
                        getUserInfo(get_user_info_url);
                    }
//                            LogUtil.e("onResp wxResponse:" + response1.body());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        finish();
    }

    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param user_info_url
     */
    private void getUserInfo(String user_info_url) {
        OkGo.<String>get(user_info_url).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                ThirdPartyLoginBean bean = new Gson().fromJson(response.body(), ThirdPartyLoginBean.class);
                if(null != bean){
                    EventBus.getDefault().post(bean);
                } else {
                    Tips.showTips(WXEntryActivity.this, "授权失败!");
                }
                WXEntryActivity.this.finish();
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID", urlEnodeUTF8(Constants.WX_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET", urlEnodeUTF8(Constants.WX_SECRET_KEY));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN", urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
